package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.admin.model.formbean.crowd.OfflineConfirmPaymentFormBean;
import com.info.zhiduoduo.admin.model.formbean.crowd.QueryCrowdOfflinePayProjectFormBean;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.service.CoreBrokerageService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.repository.dto.crowdsource.CrowdOfflinePayProjectListDto;
import com.info.zhiduoduo.repository.dto.crowdsource.DetailedPersonnelListDto;
import com.info.zhiduoduo.repository.dto.crowdsource.OfflinePayProjectExportDto;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceProject;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceProjectItem;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceTradeRecord;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceTradeRecordItem;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceTradeRecordItemMapper;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceTradeRecordMapper;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CrowdOfflinePayProjectService extends BaseService {

    @Resource
    CrowdsourceProjectMapper crowdsourceProjectMapper;

    @Resource
    CrowdsourceTradeRecordItemMapper crowdsourceTradeRecordItemMapper;

    @Resource
    CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;

    @Resource
    CoreBrokerageService coreBrokerageService;

    @Resource
    CrowdsourceTradeRecordMapper crowdsourceTradeRecordMapper;

    public SmartResult queryCrowdOfflinePayProject(BaseSimpleFormBean<QueryCrowdOfflinePayProjectFormBean> formBean){
        if(null == formBean || null == formBean.getReqdata()){
            return errorParamSmartResult();
        }
        //开始日期
        Date startDate = formBean.getReqdata().getStartDate();
        //结束日期
        Date endDate = formBean.getReqdata().getEndDate();
        if (startDate == null) {
            startDate = new Date(0);
        }
        if (endDate == null) {
            endDate = new Date();
        }
        //企业名称
        String companyName = formBean.getReqdata().getCompanyName();
        //状态
        int state = formBean.getReqdata().getState();
        if(1 == state){
            state = 2;
        } else if (2 == state) {
            state = 3;
        } else if (3 == state) {
            state = 4;
        } else {
            state = 0;
        }
        Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
        List<CrowdOfflinePayProjectListDto> offlinePayProjectListDtoList = crowdsourceProjectMapper.queryOfflinePayProjectByCondition(startDate,endDate,companyName,state);
        return smartResult(offlinePayProjectListDtoList, page.getTotal(), page.getPages(), page.getPageNum());
    }

    public SmartResult queryDetailedPersonnelById(BaseSimpleFormBean<Integer> formBean){
        if(null == formBean || null == formBean.getReqdata() || 0 == formBean.getReqdata()){
            return errorParamSmartResult();
        }
        int id = formBean.getReqdata();
        List<DetailedPersonnelListDto> list = crowdsourceTradeRecordItemMapper.queryDetailedPersonnelById(id);
        return smartResult(list);
    }

    @Transactional
    public SmartResult confirmPayment(BaseSimpleFormBean<OfflineConfirmPaymentFormBean> formBean){
        if(null == formBean || null == formBean.getReqdata()){
            return errorParamSmartResult();
        }
        OfflineConfirmPaymentFormBean confirmPaymentFormBean = formBean.getReqdata();
        //获取付款记录
        CrowdsourceTradeRecordItem crowdsourceTradeRecordItem = new CrowdsourceTradeRecordItem().selectById(confirmPaymentFormBean.getId());
        if(null == crowdsourceTradeRecordItem){
            return smartResult(StatusMsg.StatusMsg_444);
        }
        //修改支付状态
        crowdsourceTradeRecordItem.setStatus(2).setErrorMsg("线下已付款").setFinishtime(new Date()).setAdminid(formBean.getUserid());
        if(crowdsourceTradeRecordItemMapper.updateById(crowdsourceTradeRecordItem) <= 0){
            LogUtil.error("更新支付记录失败！主键：" + confirmPaymentFormBean.getId());
            return smartResult(StatusMsg.StatusMsg_199);
        }
        //更新支付凭证与备注
        CrowdsourceProjectItem projectItem = new CrowdsourceProjectItem().selectById(crowdsourceTradeRecordItem.getProjectItemId());
        if(null == projectItem){
            return smartResult(StatusMsg.StatusMsg_608);
        }
        projectItem.setPayVoucher(confirmPaymentFormBean.getPayVoucher()).setPayRemarks(confirmPaymentFormBean.getPayRemarks());
        if(crowdsourceProjectItemMapper.updateById(projectItem) <= 0){
            LogUtil.error("更新支付凭证与备注失败！支付ID：" + confirmPaymentFormBean.getId());
            return smartResult(StatusMsg.StatusMsg_199);
        }
        return handleRelationInfo(crowdsourceTradeRecordItem.getProjectid());
    }

    private SmartResult handleRelationInfo(int projectId){
        //查询项目
        CrowdsourceProject project = new CrowdsourceProject().selectById(projectId);
        if(null == project){
            return smartResult(StatusMsg.StatusMsg_606);
        }
        //查询所有关联项目付款记录
        List<CrowdsourceTradeRecordItem> itemList = new CrowdsourceTradeRecordItem().selectList(
                Condition.create().eq("projectid", projectId).eq("repay", 0));
        if (CollectionUtils.isEmpty(itemList)) {
            LogUtil.error("没有查询到项目关联的详细交易记录！项目ID：" + projectId);
            return smartResult(StatusMsg.StatusMsg_199);
        }
        //查询智众包项目批量代付记录
        CrowdsourceTradeRecord crowdsourceTradeRecord = new CrowdsourceTradeRecord().selectOne(Condition.create().eq("projectid",projectId));
        if(null == crowdsourceTradeRecord){
            return smartResult(StatusMsg.StatusMsg_610);
        }
        //计算成功条数和金额与失败条数和金额
        int succCount = 0;
        int failCount = 0;
        BigDecimal succAmount = BigDecimal.ZERO;
        BigDecimal failAmount = BigDecimal.ZERO;
        for (CrowdsourceTradeRecordItem item : itemList) {
            Integer status = item.getStatus();
            if (status != Constants.CROWDSOURCE_BATCH_ITEM_PAID) {
                failCount++;
                failAmount = failAmount.add(item.getTradeamount());
            } else {
                succCount++;
                succAmount = succAmount.add(item.getTradeamount());
            }
        }
        crowdsourceTradeRecord.setTotalSuccCount(succCount).setTotalSuccAmount(succAmount).setTotalFailCount(failCount).setTotalFailAmount(failAmount);
        //判断是否全部付款确定项目状态
        if (succCount > itemList.size()) {
            project.setState(Constants.CROWDSOURCE_PROJECT_ALL_PAID_EX);
        } else if (succCount == itemList.size()) {
            project.setState(Constants.CROWDSOURCE_PROJECT_ALL_PAID).setFinishtime(new Date());
            coreBrokerageService.handleCrowdsourceProjectPartnerBrokerage(crowdsourceTradeRecord, project);
        } else if (succCount > 0) {
            project.setState(Constants.CROWDSOURCE_PROJECT_PART_PAID);
        } else {
            project.setState(Constants.CROWDSOURCE_PROJECT_PAYING);
        }
        //判断批次状态
        switch (project.getState()) {
            case Constants.CROWDSOURCE_PROJECT_CREATE:
                crowdsourceTradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_SUBMITTED);
                break;
            case Constants.CROWDSOURCE_PROJECT_PAYING:
            case Constants.CROWDSOURCE_PROJECT_PART_PAID:
                crowdsourceTradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_BATCH_HANDLING);
                break;
            case Constants.CROWDSOURCE_PROJECT_ALL_PAID:
            case Constants.CROWDSOURCE_PROJECT_ALL_PAID_EX:
                crowdsourceTradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_BATCH_FINISHED).setFinishtime(new Date());
                break;
            case Constants.CROWDSOURCE_PROJECT_FAILED:
            case Constants.CROWDSOURCE_PROJECT_CANCELLED:
                crowdsourceTradeRecord.setBatchStatus(Constants.CROWDSOURE_BATCH_TRADE_BATCH_FAILED).setFinishtime(new Date());
                break;
            default:
                break;
        }
        //更新项目与批量付款记录
        if(crowdsourceTradeRecordMapper.updateById(crowdsourceTradeRecord) <= 0){
            LogUtil.error("更新批量付款记录失败！项目ID：" + projectId);
            return smartResult(StatusMsg.StatusMsg_199);
        }
        if(crowdsourceProjectMapper.updateById(project) <= 0){
            LogUtil.error("更新项目失败！项目ID：" + projectId);
            return smartResult(StatusMsg.StatusMsg_199);
        }
        return smartResult();
    }

    public void exportOfflinePayProjectById(HttpServletResponse response, int projectId){
        CrowdsourceProject project = new CrowdsourceProject().selectById(projectId);
        if(null == project || null == project.getCompid()){
            LogUtil.error("没有查询到项目或企业ID为空！项目ID：" + projectId);
            return;
        }
        Company company = new Company().selectById(project.getCompid());
        if(null == company || StringUtil.isEmpty(company.getContactname())){
            LogUtil.error("没有查询到公司或企业信息有误！企业ID：" + project.getCompid());
            return;
        }
        List<OfflinePayProjectExportDto> list = crowdsourceTradeRecordItemMapper.exportOfflinePayProjectById(projectId);
        String fileName = company.getCompname() + "_" + project.getProjectTotalAmount().toString() + "_" + DateUtil.DateToStr("yyyyMMddHHmmss",project.getCreatetime());
        try {
            EasyExcel.write(getExcelOutPutStream(response, fileName), OfflinePayProjectExportDto.class).sheet("工作室").doWrite(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
